package uk.ac.cam.djjb2.mygame;

import java.io.DataInput;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class DefaultClientReplicaFactory implements ClientReplicaFactory {
	private Constructor<? extends ClientReplica> constructor;
	public DefaultClientReplicaFactory(Class<? extends ClientReplica> type) throws ReplicationException {
		constructor = getConstructor(type);
	}
	
	protected Constructor<? extends ClientReplica> getConstructor(Class<? extends ClientReplica> type, Class<?>... params) throws ReplicationException {
		try {
			return type.getConstructor(params);
		} catch (NoSuchMethodException | SecurityException e) {
			throw new ReplicationException(e);
		}
	}
	protected Constructor<? extends ClientReplica> getConstructor(Class<? extends ClientReplica> type) throws ReplicationException {
		return getConstructor(type, ClientReplicaManager.class, int.class, DataInput.class);
	}

	@Override
	public ClientReplica newInstance(ClientReplicaManager replicaManager, int id, DataInput message) throws ReplicationException {
		try {
			return constructor.newInstance(replicaManager, id, message);
		} catch (InstantiationException | IllegalAccessException
				| IllegalArgumentException e) {
			throw new ReplicationException(e);
		} catch (InvocationTargetException e) {
			throw new ReplicationException(e.getCause());
		}
	}
}
